package idsync

import (
	//"context"
	"fmt"

	"iot-base/common/dbconn"

	"iot-base/common/logger"
	//"runtime"
	"time"

	//"iot-base/common/config"

	"iot-base/common/notify"

	//"github.com/go-redis/redis/v8"
	rc "iot-base/common/redis"

	"go.uber.org/zap"
)

//var rc *redis.Client
//var ctx = context.Background()

func init() {
	// rct := redis.NewClient(&redis.Options{
	// 	Addr:     config.DBOption.RedisOption.Addr,
	// 	Password: config.DBOption.RedisOption.Password, // no password set
	// 	DB:       config.DBOption.RedisOption.Index,
	// 	PoolSize: 10, // use default DB
	// })
	// //rct.Select(config.DBOption.RedisOption.Index)
	// rc = rct
}

var thingmodel interface{}
var chanForce = make(chan string)

func ForceSynID(id string) {
	chanForce <- id
}

//BeginSynIDThrd 启动同步线程
func BeginSynIDThrd(thing interface{}) {
	thingmodel = thing
	SynIDs()
	t := time.NewTicker(8 * time.Hour)
	go func() {
		for {
			select {
			case <-t.C:
				SynIDs()
			case id := <-chanForce:
				res := dbconn.DBConnection.Raw("select count(*) from things where uid='" + id + "'")
				var num int64
				res.Scan(&num)
				if num == 1 {
					rc.SAdd("set_thing_id", id)
				}
			}
		}
	}()
}
func SynObjIDs(thing interface{}) {
	thingmodel = thing
	var ids []string
	err := dbconn.DBConnection.Model(thingmodel).Select("uid").Find(&ids).Error
	if err != nil {
		logger.Log.Error("db error", zap.Error(err))
		return
	}

	idsInredis, errRedis := rc.SMembers("set_thing_id").Result()
	if errRedis != nil {
		logger.Log.Error("Redis error", zap.Error(errRedis))
		stats := rc.GetRCClient().PoolStats()
		logger.SLog.Error("Redis error pool stats", stats)
		return
	}
	idsDB := make(map[string]bool)
	idsRedis := make(map[string]bool)
	for _, id := range ids {
		idsDB[id] = true
	}

	for _, id := range idsInredis {
		idsRedis[id] = true
	}

	fmt.Println("init finish-1")
	for _, id := range ids { //indb
		ok, _ := idsRedis[id]
		if ok == false {
			rc.SAdd("set_thing_id", id)
		}
	}
	//fmt.Println("init finish-2")
	for _, id := range idsInredis { //indb
		ok, _ := idsDB[id]
		if ok == false {
			rc.SRem("set_thing_id", id)
		}
	}
	//fmt.Println("init finish-3")

}
func SynIDs() {

	SynObjIDs(thingmodel)
	//fmt.Println("init finish-3")

}
func dirty(id string, prefix string) error {
	keys, err := rc.Keys("*" + prefix + "." + id + ".*").Result()
	if err != nil {
		return err
	}
	for _, key := range keys {
		rc.Del(key).Result()
	}

	//bmsg, err := msgpack.Marshal(msg)
	if err == nil {
		//fmt.Println("dirty " + prefix + "------------++++++++++++++++")
		//rc.Publish(ctx, "dirty."+prefix+".pubmsg", bmsg)
		notify.PubMsg(false, "dirty."+prefix, id)
	}
	return nil
}

//DirtyThing 标志位dirty
func DirtyThing(id string) error {
	//删除行业id
	rid := "bid." + id + "."
	rc.Del(rid)
	return dirty(id, "thing")
}

//DirtyTModel 标志model为dirty
func DirtyTModel(id string) error {
	return dirty(id, "model")
}

//AddThing 增加设备id
func AddThing(id string) {
	rc.SAdd("set_thing_id", id)
}

//RemoveThingID 删除thing
func RemoveThingID(id string) {
	rc.SRem("set_thing_id", id)
}

//DirtyStationChildren 清除station
func DirtyStationChildren(sid string) {
	id := "station.children." + sid + "."
	rc.Del(id)
}
